import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:url_launcher/url_launcher.dart';

import '../providers/family_providers.dart';

/// 邀请家庭成员对话框
class InviteMemberDialog extends ConsumerWidget {
  /// 构造函数
  const InviteMemberDialog({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final family = ref.watch(familyProvider);
    
    if (family == null) {
      return const AlertDialog(
        title: Text('错误'),
        content: Text('无法获取家庭信息'),
      );
    }
    
    final inviteCode = family.inviteCode;
    final inviteUrl = 'https://family-app.example.com/join?code=$inviteCode';
    
    return AlertDialog(
      title: const Text('邀请家庭成员'),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(
              '分享以下邀请码或二维码给您的家人，让他们加入您的家庭空间。',
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 16.h),
            // 邀请码显示
            Container(
              padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 16.w),
              decoration: BoxDecoration(
                color: Colors.blue.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    inviteCode,
                    style: TextStyle(
                      fontSize: 24.sp,
                      fontWeight: FontWeight.bold,
                      letterSpacing: 2.w,
                    ),
                  ),
                  SizedBox(width: 8.w),
                  IconButton(
                    icon: const Icon(Icons.copy),
                    onPressed: () => _copyToClipboard(context, inviteCode),
                    tooltip: '复制邀请码',
                  ),
                ],
              ),
            ),
            SizedBox(height: 24.h),
            // 二维码显示
            GestureDetector(
              onTap: () => _openInviteUrl(context, inviteUrl),
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey.shade300),
                  borderRadius: BorderRadius.circular(8.r),
                ),
                padding: EdgeInsets.all(8.w),
                child: QrImageView(
                  data: inviteUrl,
                  version: QrVersions.auto,
                  size: 200.w,
                  backgroundColor: Colors.white,
                  errorStateBuilder: (context, error) {
                    return Center(
                      child: Text(
                        '二维码生成失败: $error',
                        textAlign: TextAlign.center,
                      ),
                    );
                  },
                ),
              ),
            ),
            SizedBox(height: 8.h),
            const Text(
              '点击二维码可查看邀请链接',
              style: TextStyle(fontSize: 12, color: Colors.grey),
            ),
            SizedBox(height: 16.h),
            // 分享按钮
            ElevatedButton.icon(
              onPressed: () => _shareInviteCode(context, inviteCode),
              icon: const Icon(Icons.share),
              label: const Text('分享邀请码'),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
              ),
            ),
            SizedBox(height: 8.h),
            // 重新生成邀请码
            TextButton.icon(
              onPressed: () => _regenerateInviteCode(context, ref),
              icon: const Icon(Icons.refresh),
              label: const Text('重新生成邀请码'),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('关闭'),
        ),
      ],
    );
  }

  /// 复制邀请码到剪贴板
  void _copyToClipboard(BuildContext context, String text) {
    Clipboard.setData(ClipboardData(text: text));
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('邀请码已复制到剪贴板')),
    );
  }

  /// 打开邀请链接
  void _openInviteUrl(BuildContext context, String url) async {
    try {
      // 在实际应用中，这里应该使用平台特定的方式打开URL
      // 为了简化示例，这里只显示一个提示
      Clipboard.setData(ClipboardData(text: url));
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('邀请链接已复制到剪贴板')),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('无法打开链接: $e')),
      );
    }
  }

  /// 分享邀请码
  void _shareInviteCode(BuildContext context, String inviteCode) {
    // 在实际应用中，这里应该调用平台特定的分享API
    // 例如在Android上使用Intent，在iOS上使用UIActivityViewController
    // 为了简化示例，这里只显示一个提示
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('分享邀请码'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('请复制以下文本，并分享给您的家人：'),
            SizedBox(height: 16.h),
            Container(
              padding: EdgeInsets.all(16.w),
              decoration: BoxDecoration(
                color: Colors.grey.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Text(
                '我邀请你加入我的家庭空间！请使用邀请码：$inviteCode 或下载家庭空间App后输入此邀请码。',
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Clipboard.setData(ClipboardData(
                text: '我邀请你加入我的家庭空间！请使用邀请码：$inviteCode 或下载家庭空间App后输入此邀请码。',
              ));
              Navigator.pop(context);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('邀请文本已复制到剪贴板')),
              );
            },
            child: const Text('复制文本'),
          ),
        ],
      ),
    );
  }

  /// 重新生成邀请码
  void _regenerateInviteCode(BuildContext context, WidgetRef ref) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('重新生成邀请码'),
        content: const Text('重新生成邀请码后，旧的邀请码将失效。确定要继续吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              ref.read(familyProvider.notifier).regenerateInviteCode();
              Navigator.pop(context);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('邀请码已重新生成')),
              );
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
}
